import { getAddressList } from '@/services/systemAddress';
import ButtonGroup, { Button } from '../../ButtonGroup';
import { View, Text } from '@tarojs/components';
import { useEffect, useState } from 'react';
import { useRequest } from 'taro-hooks';
import styles from './style.scss';
import Tree from '../../Tree';
import SelectNode from '../SelectNode';
import { pxTransform } from '@tarojs/taro';

type Props = {
  value?: any;
  onChange?: (date: Props['value']) => void;
  extraParams?: any;
  tip?: string;
};

const buildNodeTree = (data: API.Address[]) => {
  return data?.map?.((item) => ({
    label: item.qhmc,
    key: item.id,
    isLeaf: !item.sfyzjd,
  }));
};

export default (props: Props) => {
  const { onChange, value, extraParams, tip } = props;

  const [expandKeys, setExpandKeys] = useState<Array<string | number>>([]);

  const [selectKeys, setSelectkeys] = useState<Array<string | number>>([]);
  const [tree, setTree] = useState<any[]>([]);
  const [visible, setVisible] = useState(false);

  useRequest(getAddressList, {
    onSuccess(res) {
      setTree(buildNodeTree(res));
    },
    defaultParams: [extraParams],
  });

  const { run: getChildren } = useRequest(getAddressList, {
    manual: true,
  });

  useEffect(() => {
    setSelectkeys(value);
  }, [value]);

  return (
    <>
      <SelectNode
        onClick={() => setVisible(true)}
        value={
          <>
            <Text
              className={styles.current}
              style={{ marginRight: pxTransform(16) }}
            >
              当前选择地区：{value?.length || 0}
            </Text>
            <Button type="primary" size="small">
              选择
            </Button>
          </>
        }
      />

      <View
        className={styles.selectContainer}
        style={{ display: visible ? 'flex' : 'none' }}
      >
        {tip && (
          <View className={styles.header}>
            <View className={styles.tip}>{tip}</View>
          </View>
        )}
        <View className={styles.listWrap}>
          <Tree
            onSelect={(e) => setSelectkeys(e || [])}
            checkedKeys={selectKeys}
            isMultiple
            onExpand={(e) => setExpandKeys(e || [])}
            checkStrictly={false}
            style={{ flex: 1, overflow: 'auto' }}
            onLoad={({ key }, resolve) => {
              getChildren({ ssqhid: key, sfjh: 1 }).then((res) =>
                resolve(buildNodeTree(res))
              );
            }}
            expandKeys={expandKeys}
            checkable
            tree={tree}
            lazy
            compact={false}
          />
        </View>
        <ButtonGroup>
          <Button onClick={() => setVisible(false)}>取消</Button>
          <Button
            type="primary"
            onClick={() => {
              onChange?.(selectKeys);
              setVisible(false);
            }}
          >
            确定
          </Button>
        </ButtonGroup>
      </View>
    </>
  );
};
